#include "stm32f10x.h"                  // Device header

uint8_t Time_1000ms = 0;                // 1000ms标志位
uint8_t Time_500ms = 0;                 // 500ms标志位
uint8_t Time_5ms = 0;                   // 5ms标志位

uint16_t Time_1000ms_Count = 0;         // 1000ms计数
uint16_t Time_500ms_Count = 0;          // 500ms计数
uint16_t Time_5ms_Count = 0;            // 5ms计数

void Timer_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM_InternalClockConfig(TIM2);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = 
    {
        .TIM_Period = 1000,                               // 定时器溢出时间是1ms               
        .TIM_Prescaler = 72,
        .TIM_ClockDivision = TIM_CKD_DIV1,
        .TIM_CounterMode = TIM_CounterMode_Up
    };
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
    TIM_ClearFlag(TIM2, TIM_FLAG_Update);                 //clear 更新flag to 避免马上进入更新中断

    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);


    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitTypeDef NVIC_InitStructure = 
    {
        .NVIC_IRQChannel = TIM2_IRQn,
        .NVIC_IRQChannelPreemptionPriority = 0,
        .NVIC_IRQChannelSubPriority = 0,
        .NVIC_IRQChannelCmd = ENABLE
    };
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM2, ENABLE);
}

//定时器中断服务函数
/**
 * @brief TIM2中断处理函数
 * 
 * 定时器溢出时间是1ms，所以每1ms会进入一次中断。
 * 
 * 此函数是TIM2的中断处理函数。当TIM2更新中断发生时，会调用此函数。
 * 它会增加Time_1000ms_Count和Time_5ms_Count变量的值，并检查Time_1000ms_Count是否达到1000，
 * Time_500ms_Count是否达到500，以及Time_5ms_Count是否达到5。如果满足任何条件，
 * 则会将相应的Time_1000ms、Time_500ms或Time_5ms标志设置为1。
 * 
 * @param None
 * @retval None
 */
void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
        Time_1000ms_Count++;
        Time_5ms_Count++;
        if (Time_1000ms_Count >= 1000)
        {
            Time_1000ms_Count = 0;
            Time_1000ms = 1;
        }
        if (Time_500ms_Count >= 500)
        {
            Time_500ms_Count = 0;
            Time_500ms = 1;
        }
        if (Time_5ms_Count >= 5)
        {
            Time_5ms_Count = 0;
            Time_5ms = 1;
        }
    }
}
